﻿using Demo.Common;
using Demo.Web.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Demo.Web.tools
{
    /// <summary>
    /// wxapi 的摘要说明
    /// </summary>
    public class wxapi : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string opt = DTRequest.GetString("opt");
            switch (opt)
            {
                case "onLogin": onLogin(context); break;      //微信登录
                case "uploadimage":  EditorUploadImage(context); break; //编辑器上传图片
                case "submitform": submitform(context); break;//表单提交
            }
        }

        /// <summary>
        /// 微信登录
        /// </summary>
        public void onLogin(HttpContext context)
        {
            BLL.xcxconfig confing_bll = new BLL.xcxconfig();
            Model.xcxconfig confing_model = confing_bll.loadConfig();
            string code = DTRequest.GetString("code");
            string url = string.Format(DTKeys.XCX_LOGIN_URL, confing_model.AppId, confing_model.AppSecret, code);
            string res = Utils.HttpGet(url);
            Dictionary<string, object> dr = JsonHelper.DataRowFromJSON(res);
            try
            {
                string openid = dr["openid"].ToString();
                string session_key = dr["session_key"].ToString();
                BLL.weixin_user bll = new BLL.weixin_user();
                //根据openid查询数据库，如果不存在则添加用户
                if (!bll.Exists("openid", openid))
                {
                    Model.weixin_user model = new Model.weixin_user();
                    model.openid = openid;
                    model.session_key = session_key;
                    model.user_name = bll.GetRandomName(6);
                    int id = bll.Add(model);
                    if (id > 0)
                    {
                        model.id = id;
                        context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "新用户添加成功！",model)));
                        //context.Response.Write("{\"status\": 1, \"msg\": \"新用户添加成功！\", \"data\": " + JsonHelper.ObjectToJSON(model) + "}");
                        //Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "新用户添加成功！", model)));
                        //Response.End();
                    }
                    else
                    {
                        context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "添加用户失败！", model)));
                        // context.Response.Write("{\"status\": 0, \"msg\": \"添加用户失败！\", \"data\": \"\"}");
                        //Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "添加用户失败！", res)));
                        //Response.End();
                    }
                }
                else
                {
                    Model.weixin_user model = bll.GetModel(openid);
                    model.session_key = session_key;
                    bll.Update(model);
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "用户存在！", model)));
                    //context.Response.Write("{\"status\": 1, \"msg\": \"用户存在！\", \"data\": " + JsonHelper.ObjectToJSON(model) + "}");
                    //Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "用户存在！", model)));
                    //Response.End();
                }
            }
            catch (System.Collections.Generic.KeyNotFoundException)
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", $"获取openid失败！code:{dr["errcode"]},ermsg{dr["errmsg"]}")));
                //Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", $"获取openid失败！code:{dr["errcode"]},ermsg{dr["errmsg"]}")));
                //Response.End();
            }
        }


        /// <summary>
        /// 上传图片
        /// </summary>
        private void EditorUploadImage(HttpContext context)
        {
            bool _iswater = false; //默认不打水印
            HttpPostedFile upFile = context.Request.Files["upfile"];
            FileSave(context, upFile, _iswater);
        }

        /// <summary>
        /// 统一保存文件
        /// </summary>
        private void FileSave(HttpContext context, HttpPostedFile upFiles, bool isWater)
        {
            if (upFiles == null)
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请选择要上传文件！")));
                //showError(context, "请选择要上传文件！");
                return;
            }
            //检查是否允许匿名上传
            /*if (sysConfig.fileanonymous == 0 && !new ManagePage().IsAdminLogin() && !new BasePage().IsUserLogin())
            {
                showError(context, "禁止匿名非法上传！");
                return;
            }*/
            //获取文件信息
            string fileName = upFiles.FileName;
            byte[] byteData = FileHelper.ConvertStreamToByteBuffer(upFiles.InputStream); //获取文件流
            //开始上传
            string remsg = new UpLoad().FileSaveAs(byteData, fileName, false, isWater);
            Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(remsg);
            string status = dic["status"].ToString();
            string msg = dic["msg"].ToString();
            if (status == "0")
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", msg)));
                //showError(context, msg);
                return;
            }
            string filePath = dic["path"].ToString(); //取得上传后的路径
            imginfo imgmodel = new imginfo();
            imgmodel.Filename = fileName;
            imgmodel.Fileurl = filePath;
            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "上传文件成功！", imgmodel)));
            //showSuccess(context, fileName, filePath); //输出成功提示
        }

        /// <summary>
        /// 表单提交
        /// </summary>
        /// <param name="context"></param>
        private void submitform(HttpContext context)
        {
            string patient_name = DTRequest.GetString("patient_name");
            string patient_cardid = DTRequest.GetString("patient_cardid");
            int purpose = DTRequest.GetInt("purpose",0);
            int type = DTRequest.GetInt("type",0);
            int number = DTRequest.GetInt("number",0);
            string dis_time = DTRequest.GetString("dis_time");
            string patient_number = DTRequest.GetString("patient_number");
            string accept_name = DTRequest.GetString("accept_name");
            string accept_mobile = DTRequest.GetString("accept_mobile");
            string area = DTRequest.GetString("area");
            string accept_address = DTRequest.GetString("accept_address");
            int applicant_type = DTRequest.GetInt("applicant_type",0);
            string applicant_patientname = DTRequest.GetString("applicant_patientname");
            string applicant_patientcardid = DTRequest.GetString("applicant_patientcardid");
            string applicant_patientmobile = DTRequest.GetString("applicant_patientmobile");
            string agent_patientname = DTRequest.GetString("agent_patientname");
            string agent_patientcardid = DTRequest.GetString("agent_patientcardid");
            string agent_patientmobile = DTRequest.GetString("agent_patientmobile");
            string patient_cardphoto1 = DTRequest.GetString("patient_cardphoto1");
            string patient_cardphoto2 = DTRequest.GetString("patient_cardphoto2");
            string patient_cardphoto3 = DTRequest.GetString("patient_cardphoto3");
            string agent_photo = DTRequest.GetString("agent_photo");
            string agent_cardphoto1 = DTRequest.GetString("agent_cardphoto1");
            string agent_cardphoto2 = DTRequest.GetString("agent_cardphoto2");
            string agent_cardphoto3 = DTRequest.GetString("agent_cardphoto3");
            if (string.IsNullOrEmpty(patient_name) || string.IsNullOrEmpty(patient_cardid))
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写患者姓名和身份证号！")));
                return;
            }
            if (purpose == 0)
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请选择病案用途！")));
                return;
            }
            if (type == 2)//病案用途是邮寄时，需填写收件人信息
            {
                if (string.IsNullOrEmpty(accept_name)) 
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写收件人姓名！")));
                    return;
                }
                if (string.IsNullOrEmpty(accept_mobile))
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写收件人姓名！")));
                    return;
                }
                if (string.IsNullOrEmpty(area))
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请填写所属省份区域信息！")));
                    return;
                }
                if (string.IsNullOrEmpty(accept_address))
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写收件人地址！")));
                    return;
                }
            }
            if (number == 0)//复印份数
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "复印份数不能为0！")));
                return;
            }
            if (string.IsNullOrEmpty(dis_time))
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写出院日期！")));
                return;
            }
            if (applicant_type != 0)
            {
                if (string.IsNullOrEmpty(applicant_patientname) || string.IsNullOrEmpty(applicant_patientcardid) || string.IsNullOrEmpty(applicant_patientmobile))
                {
                    context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "患者姓名、身份证号、手机号不能为空！")));
                    return;
                }
                switch (applicant_type)
                {
                    case 1://申请类型为本人

                        if (string.IsNullOrEmpty(patient_cardphoto1) || string.IsNullOrEmpty(patient_cardphoto2) || string.IsNullOrEmpty(patient_cardphoto3)) {
                            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请上传患者身份证正面、反面以及手持身份证照片！")));
                            return;
                        }
                        break;
                    case 2://申请类型为代理人
                        if (string.IsNullOrEmpty(agent_patientname) || string.IsNullOrEmpty(agent_patientcardid) || string.IsNullOrEmpty(agent_patientmobile))
                        {
                            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请填写代办人的姓名、身份证号以及手机号！")));
                            return;
                        }
                        if (string.IsNullOrEmpty(patient_cardphoto1) || string.IsNullOrEmpty(patient_cardphoto2)) {
                            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请上传患者身份证正面及反面身份证照片！")));
                            return;
                        }
                        if (string.IsNullOrEmpty(agent_photo))
                        {
                            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请上传代办授权书！")));
                            return;
                        }
                        if (string.IsNullOrEmpty(agent_cardphoto1) || string.IsNullOrEmpty(agent_cardphoto2) || string.IsNullOrEmpty(agent_cardphoto3))
                        {
                            context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "请上传代办人的身份证正面、反面以及手持身份证照片！")));
                            return;
                        }
                        break;
                }
            }
            else {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写申请类型！")));
                return;
            }

            Model.patient model = new Model.patient();
            model.patient_name = patient_name;
            model.patient_cardid = patient_cardid;
            model.purpose = purpose;
            model.type = type;
            model.number = number;
            model.dis_time = Utils.StrToDateTime(dis_time);
            model.patient_number = patient_number;
            model.accept_name = accept_name;
            model.accept_mobile = accept_mobile;
            model.area = area;
            model.accept_address = accept_address;
            model.applicant_type = applicant_type;
            model.applicant_patientname = applicant_patientname;
            model.applicant_patientcardid = applicant_patientcardid;
            model.applicant_patientmobile = applicant_patientmobile;
            model.agent_patientname = agent_patientname;
            model.agent_patientcardid = agent_patientcardid;
            model.agent_patientmobile = agent_patientmobile;
            model.patient_cardphoto1 = patient_cardphoto1;
            model.patient_cardphoto2 = patient_cardphoto2;
            model.patient_cardphoto3 = patient_cardphoto3;
            model.agent_photo = agent_photo;
            model.agent_cardphoto1 = agent_cardphoto1;
            model.agent_cardphoto2 = agent_cardphoto2;
            model.agent_cardphoto3 = agent_cardphoto3;

            BLL.patient bll = new BLL.patient();
            if (bll.Add(model) > 0)
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("y", "填写表单成功！",model)));
                return;
            }
            else
            {
                context.Response.Write(JsonHelper.ObjectToJSON(JsonHelper.New("n", "填写表单失败！")));
                return;
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class imginfo {
        public imginfo() { }
        protected string filename;
        protected string fileurl;

        public string Filename { get => filename; set => filename = value; }
        public string Fileurl { get => fileurl; set => fileurl = value; }
    }
}